import 'dart:async';

import 'package:flutter/material.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:qunaimedical/im/conversations_page.dart';
import 'package:qunaimedical/im/im_utils.dart';
import 'package:qunaimedical/pages/me.dart';
import 'package:qunaimedical/pages/summary.dart';
import 'package:qunaimedical/pages/web_page.dart';
import 'package:qunaimedical/utils/event_bus_manager.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';

class HomePage extends StatefulWidget {
  static const String routeName = '/home';

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  final String _tag = '_HomePageState';
  List<String> _tabImages = [
    'assets/images/ic_tab_home.png',
    'assets/images/ic_tab_quan.png',
    'assets/images/ic_tab_chat.png',
    'assets/images/ic_tab_me.png',
  ];
  List<String> _tabTitles = ['首页', '会诊', '消息', '我的'];

  int _tabIndex = 0;
  final _pageController = PageController();
  late StreamSubscription _eventSubscription;
  bool _hasUnreadMsg = false;
  DateTime? lastPopTime;

  @override
  void initState() {
    super.initState();
    _eventSubscription = eventBus.on<EventBusMessage>().listen((event) {
      if (event == EventBusMessage.updateUnreadMsgFlag) {
        _getUnreadMsgCount();
      }
      if (event == EventBusMessage.jump2ConsultationCenter) {
        _pageController.jumpToPage(1);
      }
      if (event == EventBusMessage.jump2Conversations) {
        _pageController.jumpToPage(2);
      }
      if (event == EventBusMessage.jump2Me) {
        _pageController.jumpToPage(3);
      }
    });
    IMUtils.initIMSDK().then((_) {
      // 添加环信回调监听
      _addChatListener();
      _getUnreadMsgCount();
    });
  }

  void _addChatListener() {
    EMClient.getInstance.chatManager.addEventHandler(
      _tag,
      EMChatEventHandler(
        onMessagesReceived: (messages) => _getUnreadMsgCount(),
      ),
    );
  }

  Future<void> _getUnreadMsgCount() async {
    int count = await EMClient.getInstance.chatManager.getUnreadMessageCount();
    if (mounted) {
      setState(() {
        _hasUnreadMsg = count > 0;
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
    _eventSubscription.cancel();
    // 移除环信回调监听
    EMClient.getInstance.chatManager.removeEventHandler(_tag);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (lastPopTime == null ||
            DateTime.now().difference(lastPopTime!) > Duration(seconds: 1)) {
          lastPopTime = DateTime.now();
          ToastUtil.show("再按一次退出");
          return Future.value(false);
        } else {
          lastPopTime = DateTime.now();
          // 退出app
          return Future.value(true);
        }
      },
      child: Scaffold(
        body: PageView(
          physics: NeverScrollableScrollPhysics(),
          children: [
            SummaryPage(),
            WebPage(
              url: Urls.CONSULTATION_CENTER,
              title: "会诊中心",
            ),
            ConversationsPage(),
            MePage(),
          ],
          controller: _pageController,
          onPageChanged: (index) {
            setState(() {
              _tabIndex = index;
            });
          },
        ),
        bottomNavigationBar: BottomNavigationBar(
          items: List.generate(
            _tabImages.length,
            (index) {
              Widget unreadFlag = Positioned(
                top: 0.0,
                right: 4.0,
                child: Offstage(
                  offstage: !(index == 2 && _hasUnreadMsg),
                  child: Container(
                    width: 10,
                    height: 10,
                    decoration: BoxDecoration(
                      color: Colors.redAccent,
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                    ),
                  ),
                ),
              );
              EdgeInsetsGeometry _padding =
                  EdgeInsets.only(left: 10, right: 10, top: 0, bottom: 3);
              return BottomNavigationBarItem(
                icon: Stack(
                  children: [
                    Container(
                      padding: _padding,
                      child: Image.asset(
                        _tabImages[index],
                        width: 24,
                        color: _tabIndex == index
                            ? Theme.of(context).primaryColor
                            : null,
                      ),
                    ),
                    unreadFlag,
                  ],
                ),
                label: _tabTitles[index],
              );
            },
          ),
          currentIndex: _tabIndex,
          onTap: (index) {
            _pageController.jumpToPage(index);
            if (index == 1) {
              eventBus.fire(EventBusMessage.refreshWebpage);
            }
          },
          selectedItemColor: Colors.black87,
          type: BottomNavigationBarType.fixed,
          selectedFontSize: 14,
          unselectedFontSize: 14,
        ),
      ),
    );
  }
}
